//
//  BinaryCodeScanner.swift
//  E-CycleForShop
//
//  Created by enghou on 17/3/5.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit
import AVFoundation
class BinaryCodeScanner: NSObject,AVCaptureMetadataOutputObjectsDelegate {
    var device : AVCaptureDevice?
    var input : AVCaptureDeviceInput?
    var output : AVCaptureMetadataOutput?
    var session : AVCaptureSession?
    var preview : AVCaptureVideoPreviewLayer?
    weak var view : UIView?
    init(view : UIView,success : (String)->Void) {
        super.init()
        self.configDevice()
    }
    
    @objc fileprivate func configDevice()->Void{
        let authorization = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
        if authorization == AVAuthorizationStatus.denied {
//            self.alertSomeMessage(title: YXAlertTitle, content: "请打开隐私设置", sureTitle: YXConfirmTitle, cancelTitle: YXCancelTitle, ensureAction: { (alert) in
//                OpenHandler.openSettings()
//            }, cancelAction: { (alert) in
//                
//            })
            return
        }else{
            device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
            do {
                input = try AVCaptureDeviceInput.init(device: device)
                output = AVCaptureMetadataOutput.init()
                output!.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
                session = AVCaptureSession.init()
                session!.sessionPreset = AVCaptureSessionPresetHigh
                if session!.canAddInput(input!){
                    session!.addInput(input!)
                }
                if session!.canAddOutput(output!) {
                    session!.addOutput(output!)
                }
                let originX = YXDeviceWidth / 4
                let originY = YXDeviceHeight / 2 - originX
                print(output!.rectOfInterest)
                output!.rectOfInterest = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 1, height: 1))
                output!.rectOfInterest = CGRect.init(origin: CGPoint.init(x: 0.25, y: originY / YXDeviceHeight), size: CGSize.init(width: 0.5, height: 0.5 * YXDeviceWidth / YXDeviceHeight))
                output!.metadataObjectTypes = [AVMetadataObjectTypeQRCode,
                                               AVMetadataObjectTypeEAN13Code,
                                               AVMetadataObjectTypeEAN8Code,
                                               AVMetadataObjectTypeCode93Code,
                                               AVMetadataObjectTypeCode128Code]
                preview = AVCaptureVideoPreviewLayer.init(session: session!)
                preview!.videoGravity = AVLayerVideoGravityResizeAspectFill
                preview!.frame = self.view!.bounds
                self.view!.layer.addSublayer(preview!)
                if device!.isFocusPointOfInterestSupported && device!.isFocusModeSupported(AVCaptureFocusMode.autoFocus) {
                    do {
                        try input!.device!.lockForConfiguration()
                        input!.device!.focusMode = AVCaptureFocusMode.continuousAutoFocus
                        input!.device!.unlockForConfiguration()
                    } catch {
                        print(error.localizedDescription)
                    }
                }
            } catch  {
                print(error)
            }
        }
    }
    
    func run() -> Void {
        if session!.isRunning {
            return
        }
        session!.startRunning()
    }
    
    func stop() -> Void {
        if session!.isRunning {
            session!.stopRunning()
        }
    }
    
    //delegates
    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
        var stringVal = ""
        if metadataObjects.count > 0 {
            session!.stopRunning()
            let metaDataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
            stringVal = metaDataObj.stringValue
        }
        print(stringVal)
    }
}
